package cn.kgc.tangcco.utils.fdfs;

import cn.hutool.setting.dialect.Props;
import org.csource.common.MyException;
import org.csource.fastdfs.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author 李昊哲
 * @Description FastDFS上传工具类
 * @create 2020/9/6 下午2:44
 */
public abstract class BaseFastDFSUtil {
    /**
     * 配置文件
     */
    private final static String propFilePath = "fastdfs-client.properties";
    private static Props props = new Props("config.properties");
    private static String http_protocol=props.getProperty("http_protocol");
    private static String fdfs_storage_proxy_ip=props.getProperty("fdfs_storage_proxy_ip");
    private static String fdfs_storage_proxy_port=props.getProperty("fdfs_storage_proxy_port");
    static {
        try {
            // 加载配置文件
            ClientGlobal.initByProperties(propFilePath);
        } catch (IOException | MyException e) {
            e.printStackTrace();
        }
    }

    /**
     *
     * @param inputStream   上传文件自己输入流
     * @return  http访问url地址
     * @throws Exception
     */
    public static String upload(InputStream inputStream,String file_ext_name) throws Exception {
        TrackerClient tracker = new TrackerClient();
        TrackerServer trackerServer = tracker.getTrackerServer();
        StorageServer storageServer = null;
        StorageClient storageClient = new StorageClient(trackerServer, storageServer);
        int length = inputStream.available();
        byte[] bytes = new byte[length];
        inputStream.read(bytes);
        String[] result = storageClient.upload_file(bytes, file_ext_name, null);
        storageClient.close();
        // http://172.16.70.100:8888/group1/M00/00/00/rBBGZF9UhCWAEAd7ABQFpIoEzNM450.png
        return http_protocol + fdfs_storage_proxy_ip + fdfs_storage_proxy_port +"/" +result[0] + "/" + result[1];
    }
}
